<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="search">
        <el-form-item>
          <el-input v-model="search.key" placeholder="权限名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="queryData">查询</el-button>
        </el-form-item>

      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="pageInfo.data" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="权限名称" width="120" sortable>
      </el-table-column>
      <el-table-column prop="url" label="权限路径" width="120" sortable>
      </el-table-column>
      <el-table-column prop="descs" label="权限描述" width="180" sortable>
      </el-table-column>
      <el-table-column prop="sn" label="唯一标识" width="240" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="父权限" width="150" sortable>
      </el-table-column>

    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="search.currentPage"
          :page-sizes="[10, 20]"
          :page-size="100"
          style="float: right"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total">
      </el-pagination>

    </el-col>


    <!--新增和修改界面-->
    <el-dialog title="新增" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" ref="addForm">
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="权限路径" prop="url">
          <el-input v-model="saveForm.url" auto-complete="off"></el-input>
        </el-form-item>


        <el-form-item label="上级部门">
          <el-cascader v-model="saveForm.parent"
                       :options="deptTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"
                       clearable></el-cascader>
        </el-form-item>

        <el-form-item label="部门状态" prop="state">
          <el-input v-model="saveForm.state" auto-complete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>

export default {
  data() {
    return {
      deptTree: [],  //后台查出来的父部门即其子部门数据
      search: {
        key: '',
        pageSize: 10,
        currentPage: 1
      },
      pageInfo: {
        data: [],
        total: 0,
      },
      listLoading: false,
      sels: [],//列表选中列
      saveFormVisible: false,
      saveForm: {
        id: null,
        name: "",
        intro: "",
        manager: {
          id: null,
          username: ""
        },
        parent: {
          id: null,
          name: "",
        },
        state: ""
      }

    }
  },
  methods: {

    //获取部门主管 数组
    getManagers() {
      //发送请求
      this.$http.get("/employee")
          .then(res => {
            res = res.data
            if (res.success) {
              this.employees = res.data;
            }
          })
          .catch(res => {
          })
    },

    // 点击新增
    handleAdd() {
      this.saveFormVisible = true; //显示弹出框
      this.saveForm = {
        id: null,
        name: "",
        intro: "",
        manager: {
          id: null,
          username: ""
        },
        parent: {
          id: null,
          name: "",
        },
        state: ""
      }
      //调用查询部门主管的方法
      this.getManagers();
      //调用查询部门树的方法
      this.getDeptTree();
    },

    // 点击查询的方法
    queryData() {
      this.search.currentPage = 1
      this.getPermissions()
    },

    // 每页条数变动的时候
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.search.pageSize = val
      this.getPermissions()
    },

    //性别显示转换
    formatSex: function (row, column) {
      return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
    },
    handleCurrentChange(val) {
      // val 指的是当前的页数
      this.search.currentPage = val;
      this.getPermissions();
    },

    //获取权限列表
    getPermissions() {
      this.listLoading = true;
      this.$http.post("/permission", this.search)
          .then(res => {
            this.listLoading = false;
            res = res.data;
            console.log(res)
            if (res.success) {
              // this.permissions = res.data.data
              // this.total = res.data.total
              this.pageInfo = res.data; //将查出的数据总数和数据赋给pageInfo，进而给列表传数据并显示
            }
          })
          .catch(res => {
          })
      // this.listLoading = true;

    },

    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {  //点击确认
        this.listLoading = true;
        this.$http.delete("/permission/" + row.id)  //发送删除请求，并传id
            .then(res => {
              res = res.data
              this.listLoading = false;  //加载框消失
              if (res.success) {
                this.$message({type: "success", message: "删除成功"});
              } else {
                this.$message.error("删除失败" + res.msg)
              }
              this.search.currentPage = 1; //删完回到第一页
              this.getPermissions();  //重新查询
            })
            .catch(res => {
            })

      }).catch(() => {

      });
    },


    //显示新增和修改界面
    handleSave: function (index, row) {
      console.log(row)
      this.saveFormVisible = true;
      this.saveForm = JSON.parse(JSON.stringify(row)); //数据回显,深拷贝
      //父部门回显
      var split = row.path.split("/");
      console.log(split)
      var data = []
      for (let i = 1; i < split.length - 1; i++) {
        data.push(Number.parseInt(split[i]))
      }
      console.log(data)
      this.saveForm.parent = data;

      //判断父部门 是否为空
      if (!row.parent) {
        this.saveForm.parent = {
          id: null,
          name: ""
        }
      }

      //判断管理者 是否为空
      if (!row.manager) {
        this.saveForm.manager = {
          id: null,
          username: ""
        }
      }

      //调用查询部门主管的方法
      this.getManagers();
      //调用查询部门树的方法
      this.getDeptTree();
    },


    //新增和修改的提交按钮
    addSubmit: function () {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {

            //NProgress.start();
            let para = Object.assign({}, this.saveForm); //获取输入框的值
            //判断父部门
            var parent = para.parent;
            if (parent.length >= 0) {
              if (parent.length == 0) {
                para.parent = {id: null, name: ""}
              } else {
                para.parent = {id: parent[parent.length - 1], name: ""}
              }
            }

            //发送请求
            this.$http.put("/permission", para)
                .then(res => {
                  this.saveFormVisible = false; //关闭弹出框
                  this.$message({type: "success", message: "保存成功"});
                  this.getPermissions() //重新查询
                })
                .catch(res => {

                })

          });
        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },

    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => { //点击确认
        this.listLoading = true;
        //发送请求
        this.$http.patch("/permission", ids)  //发送删除请求，并传id
            .then(res => {
              res = res.data
              this.listLoading = false;  //加载框消失
              if (res.success) {
                this.$message({type: "success", message: "删除成功"});
              } else {
                this.$message.error("删除失败" + res.msg)
              }
              this.search.currentPage = 1; //删完回到第一页
              this.getPermissions();  //重新查询
            })
            .catch(res => {
            })

      }).catch(() => {

      });
    }
  },
  mounted() {
    this.getPermissions();
  }
}

</script>

<style scoped>

</style>